package com.ferry.config.server;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Collection;

/**
 * Created by daiyong
 */
public class LongPollManager {

	//多线程 使用锁
	private static Multimap<String, DeferredResult<String>> watchRequests = Multimaps.synchronizedSetMultimap(HashMultimap.create());

	public static void addDeferredResult(String nameSpace, DeferredResult deferredResult) {
		deferredResult.onCompletion(() -> {
			watchRequests.remove(nameSpace, deferredResult);
		});
		deferredResult.onTimeout(()->{
		});
		watchRequests.put(nameSpace, deferredResult);
	}

	public static void notifyDeferredResult(String nameSpace, String updateMsg) {
		Collection<DeferredResult<String>> deferredResults = watchRequests.get(nameSpace);

		/**
		 * 依次唤醒各个客户端
		 */
		for (DeferredResult<String> deferredResult : deferredResults) {
			deferredResult.setResult(updateMsg);
		}

	}

}
